<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/9/29
 * Time: 15:54
 */

namespace addons\jieziaddress\controller;

use app\common\controller\Api as AApi;

/**
 * @ApiSector (地址管理)
 * @package addons\jieziaddress\controller
 */
class Api extends AApi
{
//    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected function _initialize()
    {
        $this->request->request(['token' => input('token')]);
        parent::_initialize(); // TODO: Change the autogenerated stub
    }
    /**
     * @ApiTitle (地址列表)
     * @ApiMethod (POST)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1632991219",
    "data": [
    {
    "cont": "飞洒地方啊发生的法撒旦法撒旦发大水",
    "phone": "15011111222",
    "name": "bbb3333332",
    "id": 55,
    "is_default": 0
    }
    ]
    })
     */
    public function get_list()
    {
        $address_model = new \addons\jieziaddress\model\JieziaddressUserAddress();
        $this->success('ok', $address_model->addressList($this->auth->getUserinfo()['id']));
    }

    /**
     * @ApiTitle (地址详细)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", require=true, sample="0")
     * @ApiParams (name="default", type="integer", require=true, sample="0", description="获取默认地址")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function info()
    {
        $id = intval(input('id'));//token\address_id[地址ID]
        $user = $this->auth->getUserinfo()['id'];
        $default = input('default', 0, 'intval');
        $address_model = new \addons\jieziaddress\model\JieziaddressUserAddress();
        $thing = $address_model->info($user, $id, $default);

        $this->success('查询成功', $thing);
    }
    /**
     * @ApiTitle (地址编辑)
     * @ApiSummary (编辑时传递id)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", require=true, sample="0", description="编辑时传递id")
     * @ApiParams (name="phone", type="string", require=true, sample="", description="手机号码")
     * @ApiParams (name="name", type="string", require=true, sample="", description="姓名")
     * @ApiParams (name="pid", type="integer", require=false, sample="0", description="省id")
     * @ApiParams (name="cid", type="integer", require=false, sample="0", description="市id")
     * @ApiParams (name="aid", type="integer", require=false, sample="0", description="区县id")
     * @ApiParams (name="detail", type="string", require=true, sample="", description="详细地址")
     * @ApiParams (name="is_default", type="integer", require=true, sample="1", description="默认地址,1=是,0=否")
     * @ApiParams (name="lat", type="float", require=false, sample="1", description="纬度,aid为空时可用")
     * @ApiParams (name="lng", type="float", require=false, sample="1", description="经度,aid为空时可用")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function edit()
    {
        $params = input();//token\phone\name\address[用逗号拼接的字符串]\detailed_address
        $id = empty($params['id']) ? 0 : intval($params['id']);
        $user = $this->auth->getUserinfo()['id'];//用户信息
        $address_model = new \addons\jieziaddress\model\JieziaddressUserAddress();
        $item = [];
        if ($id > 0) {
            $item = $address_model->where('id', $id)->where('user_id', $user)->find();
            if (empty($item)) {
                $this->error('地址不存在');
            }
        }
        if (empty($params['phone'])) {
            $this->error('请填写手机号码');
        }

        if (!\think\Validate::make(['phone' => '/^1[3-9][0-9]\d{8}$/'])->check(['phone' => $params['phone']])) {
            $this->error('请用正确手机号');
        }
        if (empty($params['name'])) {
            $this->error('请输入姓名');
        }
        $data['phone'] = $params['phone'];
        $data['name'] = $params['name'];
        $data['province_id'] = empty($params['pid']) ? 0 : intval($params['pid']);
        $data['city_id'] = empty($params['cid']) ? 0 : intval($params['cid']);
        $data['district_id'] = empty($params['aid']) ? 0 : intval($params['aid']);
        $data['address'] = empty($params['detail']) ? '' : htmlspecialchars($params['detail']);
        $data['location'] = empty($params['location']) ? '' : htmlspecialchars($params['location']);
        $data['is_default'] = empty($params['is_default']) ? 0 : 1;
        $data['lat'] = empty($params['lat']) ? 0 : floatval($params['lat']);
        $data['lng'] = empty($params['lng']) ? 0 : floatval($params['lng']);
        $area_model = new \addons\jieziarea\model\Jieziarea();
        //type = 1 微信导入
        if ($data['lat'] > 0 && $data['lng'] > 0 && $data['district_id'] <= 0 && empty($params['type'])) {
            $return_data = $area_model->getAddressByQqmap($data['lat'], $data['lng'], 'city_name_code');

            if (!empty($return_data['district_id'])) {
                if (empty($data['location'])) {
                    $arr = [];
                    $arr['p'] = $return_data['province_name'];
                    $arr['c'] = $return_data['city_name'];
                    $arr['d'] = $return_data['district_name'];
                    if (count($arr) == 3) {
                        $data['location'] = join('|', $arr);
                    }
                }
                $data['province_id'] = $return_data['province_id'];
                $data['city_id'] = $return_data['city_id'];
                $data['district_id'] = $return_data['district_id'];
            }
        }
        //type = 1 微信导入
        if ($data['district_id'] <= 0 && !empty($params['type'])) {
            if ((!empty($params['address']['district']) || !empty($params['district']))) {
                $district = !empty($params['address']['district']) ? $params['address']['district']:$params['district'];
                $arr = $area_model->where('name', $district)->field('id, pid')->find();

                if (empty($arr['id'])) {
                    $arr = $area_model->whereLike('name', '%' . $district . '%')->field('id, pid')->find();
                }

                if (!empty($arr['id'])) {
                    $data['city_id'] = $arr['pid'];
                    $data['district_id'] = $arr['id'];
                    $data['province_id'] = $area_model->where('id', $arr['pid'])->value('pid');
                    if (empty($data['location'])) {
                        $arr = [];
                        $arr['p'] = $params['address']['province'];
                        $arr['c'] = $params['address']['city'];
                        $arr['d'] = $params['address']['district'];
                        if (count($arr) == 3) {
                            $data['location'] = join('|', $arr);
                        }
                    }
                }
            }
        }
        /*if($data['province_id'] <= 0){
            $this->error('请选择省份');
        }
        if($data['city_id'] <= 0){
            $this->error('请选择城市');
        }
        if($data['district_id'] <= 0){
            $this->error('请选择区县');
        }*/
        if (!$data['address']) {
            $this->error('请输入详细地址');
        }
        if (empty($data['location'])) {
            $arr = [];
            $area_model = new \addons\jieziarea\model\Jieziarea();
            if (!empty($data['province_id'])) {
                $arr['p'] = $area_model->where('id', $data['province_id'])->value('name');
            }
            if (!empty($data['city_id'])) {
                $arr['c'] = $area_model->where('id', $data['city_id'])->value('name');
            }
            if (!empty($data['district_id'])) {
                $arr['d'] = $area_model->where('id', $data['district_id'])->value('name');
            }
            if (count($arr) == 3) {
                $data['location'] = join('|', $arr);
            }
        }
        if ($data['is_default']) {//设为默认
            $thing = array(
                'is_default' => 0
            );
            $address_model->where('user_id', $user)->update($thing);
        }

        $is_create = false;
        if ($id > 0 && $item) {
            $data['updatetime'] = time();
            $result = $address_model->where('id', $id)->where('user_id', $user)->update($data);
        } else {
            if (!$address_model->where('user_id', $user)->where('is_del', 0)->count()) {
                $data['is_default'] = 1;
            }
            $is_create = true;
            $data['user_id'] = $user;
            $data['createtime'] = time();
            $result = $address_model->insertGetId($data);
            $id = $result;
        }
        if (!empty($result)) {
            $this->success($is_create ? '地址添加成功' : '地址修改成功', $id);
        } else {
            $this->error($is_create ? '地址添加失败' : '地址修改失败');
        }
    }

    /**
     * @ApiTitle (地址删除)
     * @ApiSummary ()
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", require=true, sample="0", description="id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function del()
    {
        $id = intval(input('id'));
        $user = $this->auth->getUserinfo()['id'];//用户信息
        $address_model = new \addons\jieziaddress\model\JieziaddressUserAddress();
        if ($id > 0) {
            $del = $address_model->where('id', $id)->where('user_id', $user)->update(['is_del' => 1]);
            if (!empty($del)) {
                $this->success('数据删除成功');
            } else {
                $this->error('数据删除失败');
            }
        } else {
            $this->error('地址无效');
        }
    }

    /**
     * @ApiTitle (设为默认)
     * @ApiSummary ()
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", require=true, sample="0", description="id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function set_default()
    {
        $id = intval(input('id'));
        $user = $this->auth->getUserinfo()['id'];//用户信息
        $address_model = new \addons\jieziaddress\model\JieziaddressUserAddress();
        if ($id > 0) {
            $item = $address_model->where('id', $id)->where('user_id', $user)->find();
            if (empty($item)) {
                $this->error('地址不存在');
            }
            $thing = array(
                'is_default'=>0,
                'updatetime' => time(),
            );
            $thing2 = array(
                'is_default'=>1,
                'updatetime' => time(),
            );
            $result = $address_model->where('user_id', $user)->update($thing);
            if (empty($result)) {
                $this->error('设置默认地址错误');
            }
            $result = $address_model->where('id', $id)->where('user_id', $user)->update($thing2);
            if (empty($result)) {
                $this->error('设置默认地址错误.');
            }

            $this->success('设置默认地址成功');
        } else {
            $this->error('参数无效');
        }
    }
}
